import axios from 'axios';
import {Message, MessageBox} from 'element-ui';
import md5 from 'js-md5';
import jwt from "jsonwebtoken";
import {GetQueryValue, guid} from "./index";
import store from '@/store'
import {getAppid, getToken, setAppid,} from '@/utils/auth';
import requestStatusMixin from "@/components/mixin/requestStatus";

var Base64 = require('js-base64');

const service = axios.create({
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    "tokenType": "zjw-vue",
    "API-VERSION": "1.0.0",
  },
  baseURL: process.env.VUE_APP_RBAC_HOST, // url = base url + request url
  // withCredentials: true, // 跨域请求时发送cookie
  timeout: 30000
})

// 创建一个新的 CancelToken
const cancelTokenSource = axios.CancelToken.source();
var data;
service.interceptors.request.use(
  config => {
    var appid = getAppid();
    if (!appid) {
      var req = new XMLHttpRequest();
      req.open('GET', '/', false);
      req.setRequestHeader("Cache-Control","no-cache");
      req.onreadystatechange = function() {
        if (req.readyState === 4 && req.status === 200) {
          appid = req.getResponseHeader("api-appid");
          setAppid(appid)
        }
      };
      req.send();
    }
    if (appid){
      var token = getToken();
      if (token) {
        config.headers['trainToken'] = token;
      }
      var time = new Date().getTime();
      var uuid =data = guid();
      config.headers['app-client'] = getAppid() || appid;
      config.headers['X-TIMESTAMP'] = time;
      config.headers['X-NONCE'] = uuid;
      config.headers['X-SIGN'] = md5(time + "#" + uuid + "#zjw-vue#Ul2lZUu8");
      var appAuth = {
        "appid": getAppid() || appid,
        "uid": "0",
        "time": time,
        "subject": uuid,
        "expiration": new Date().getTime(),
      };

      var tokenStr = jwt.sign(appAuth, Base64.encode(process.env.VUE_APP_SECRET_KEY));
      config.headers['appAuth'] = tokenStr;
      return config;
    }
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // console.log(response)
    // response.config.requestKey = data;
    // response = requestStatusMixin.methods.updateRequestStatus(response);
    const res = response.data;
    if (response.status === 200) {
      if (response.data.code == 1200) {
        return response.data;
      } else if (response.data.code == 8000) {
        Message("用户未登录");
        store.dispatch("user/resetToken").then(() => {
          location.reload()
        });
      }else if (response.data.code == 3001 || response.data.code ==  3002){
        window.location.href = '/401';
      } else if (response.data.code == -6) {
        MessageBox.confirm(
          "登录已失效，可以取消继续留在该页面，或者重新登录",
          "温馨提示",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }
        ).then(() => {
          store.dispatch("user/resetToken").then(() => {
            location.reload()
          });
        });
        return Promise.reject(res); // 返回reject，停止后续请求
      } else {
        return Promise.reject(res)
      }
    }else {
      return Promise.reject(res)
    }

  },
  error => {
    return Promise.reject(error)
  }
)

export default service
